import {
  createToolbarConfig,
  IModelService,
  IToolbarItemOptions,
  NsGroupCmd,
  uuidv4,
  XFlowGroupCommands,
  XFlowNodeCommands,
  XFlowGraphCommands,
  NsGraphCmd,
  NsNodeCmd,
  IconStore,
  MODELS,
  IGraphCommand,
  useXFlowApp,
  NsGraph,
  // useModelAsync
} from '@antv/xflow'

import {
  UngroupOutlined,
  SaveOutlined,
  GroupOutlined,
  GatewayOutlined,
  UndoOutlined,
  RedoOutlined,
  VerticalAlignTopOutlined,
  VerticalAlignBottomOutlined,
  CopyOutlined,
  SnippetsOutlined,
  FolderOpenOutlined,
  CloseOutlined
} from '@ant-design/icons'
import { Message, MessageBox } from 'element-react';
import { db } from "./db/index"
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
import * as Graph from './components/graph'

import { useEffect, useRef, useState } from "react";

const GROUP_NODE_RENDER_ID = 'GROUP_NODE_RENDER_ID'

/** 系统命令 */
export namespace SystemCommands {
  const category = '系统操作'
  /** 清除画布 */
  export const CLEAR_GRAPH: IGraphCommand = {
    id: 'xflow:clear-graph',
    label: '清除',
    category,
  }
  /** 导出 */
  export const EXPORT_GRAPH: IGraphCommand = {
    id: 'xflow:export-graph',
    label: '导出',
    category,
  }
  /** 重命名节点弹窗 */
  export const SHOW_RENAME_MODAL: IGraphCommand = {
    id: 'xflow:rename-node-modal',
    label: '打开重命名弹窗',
    category,
  }
}

export namespace TOOLBAR_ITEMS {
  export const COPY = `${XFlowGraphCommands.GRAPH_COPY.id}`
  export const PASTE = `${XFlowGraphCommands.GRAPH_PASTE.id}`
}

namespace NSToolbarConfig {

  /** toolbar依赖的状态 */
  export interface IToolbarState {
    isMultiSelectionActive: boolean
    isGroupSelected: boolean
    isNodeSelected: boolean
    isUndoable: boolean
    isRedoable: boolean
    isDeleteGraph: boolean
    // isChioseGraph: boolean
  }

  export const getDependencies = async (modelService: IModelService) => {
    return [
      await MODELS.SELECTED_NODES.getModel(modelService),
      await MODELS.GRAPH_ENABLE_MULTI_SELECT.getModel(modelService),
      // await Graph.GRAPH_CHIOSE.getModel(modelService),
    ]
  }

  /** toolbar依赖的状态 */
  export const getToolbarState = async (modelService: IModelService, graphModel) => {
    // isMultiSelectionActive
    const { isEnable: isMultiSelectionActive } = await MODELS.GRAPH_ENABLE_MULTI_SELECT.useValue(modelService)
    // isGroupSelected
    const isGroupSelected = await MODELS.IS_GROUP_SELECTED.useValue(modelService)
    // isNormalNodesSelected: node不能是GroupNode
    const isNormalNodesSelected = await MODELS.IS_NORMAL_NODES_SELECTED.useValue(modelService)
    // undo redo
    const isUndoable = await MODELS.COMMAND_UNDOABLE.useValue(modelService)
    const isRedoable = await MODELS.COMMAND_REDOABLE.useValue(modelService)
    // const [isChioseGraph] = useModelAsync<Graph.GRAPH_CHIOSE.IState>({
    //   getModel: async () => Graph.GRAPH_CHIOSE.getModel(modelService),
    //   initialState: true,
    // })

    // const isChioseGraph = await Graph.GRAPH_CHIOSE.useValue(modelService)

    return {
      isUndoable,
      isRedoable,
      isNodeSelected: isNormalNodesSelected,
      isGroupSelected,
      isMultiSelectionActive,
      // isChioseGraph,
    } as NSToolbarConfig.IToolbarState
  }

  export const getToolbarItems = async (state: IToolbarState, modelService: IModelService) => {
    const operToolbarGroup: IToolbarItemOptions[] = []
    const iconToolbarGroup: IToolbarItemOptions[] = []
    const titleToolbarGroup: IToolbarItemOptions[] = []

    // let graphCurrent = {
    //   id: 0,
    //   text: "未命名",
    //   data: {}
    // }

    // const [graphData, setGraphData] = useState({})

    // const meta = await MODELS.GRAPH_META.useValue(modelService);
    // const { history } = meta.graph.current

    // /** 撤销 */
    // iconToolbarGroup.push({
    //   tooltip: '撤销',
    //   iconName: 'UndoOutlined',
    //   id: XFlowGraphCommands.UNDO_CMD.id,
    //   isEnabled: history.canUndo(),
    //   onClick: async () => {
    //     history.undo()
    //   },
    // })

    // /** 重做 */
    // iconToolbarGroup.push({
    //   tooltip: '重做',
    //   iconName: 'RedoOutlined',
    //   id: XFlowGraphCommands.REDO_CMD.id,
    //   isEnabled: history.canRedo(),
    //   onClick: async () => {
    //     history.redo()
    //   },
    // })

    /** FRONT_NODE */
    iconToolbarGroup.push({
      tooltip: '置前',
      iconName: 'VerticalAlignTopOutlined',
      id: XFlowNodeCommands.FRONT_NODE.id,
      isEnabled: state.isNodeSelected,
      onClick: async ({ commandService, modelService }) => {
        const node = await MODELS.SELECTED_NODE.useValue(modelService)
        commandService.executeCommand<NsNodeCmd.FrontNode.IArgs>(XFlowNodeCommands.FRONT_NODE.id, {
          nodeId: node?.id,
        })
      },
    })

    /** BACK_NODE */
    iconToolbarGroup.push({
      tooltip: '置后',
      iconName: 'VerticalAlignBottomOutlined',
      id: XFlowNodeCommands.BACK_NODE.id,
      isEnabled: state.isNodeSelected,
      onClick: async ({ commandService, modelService }) => {
        const node = await MODELS.SELECTED_NODE.useValue(modelService)
        commandService.executeCommand<NsNodeCmd.FrontNode.IArgs>(XFlowNodeCommands.BACK_NODE.id, {
          nodeId: node?.id,
        })
      },
    })

    /** 开启框选 */
    iconToolbarGroup.push({
      tooltip: '开启框选',
      iconName: 'GatewayOutlined',
      id: XFlowGraphCommands.GRAPH_TOGGLE_MULTI_SELECT.id,
      active: state.isMultiSelectionActive,
      onClick: async ({ commandService }) => {
        commandService.executeCommand<NsGraphCmd.GraphToggleMultiSelect.IArgs>(
          XFlowGraphCommands.GRAPH_TOGGLE_MULTI_SELECT.id,
          {},
        )
      },
    })

    /** 新建群组 */
    iconToolbarGroup.push({
      tooltip: '新建群组',
      iconName: 'GroupOutlined',
      id: XFlowGroupCommands.ADD_GROUP.id,
      isEnabled: state.isNodeSelected,
      onClick: async ({ commandService, modelService }) => {
        const cells = await MODELS.SELECTED_CELLS.useValue(modelService)
        const groupChildren = cells.map(cell => cell.id)
        commandService.executeCommand<NsGroupCmd.AddGroup.IArgs>(XFlowGroupCommands.ADD_GROUP.id, {
          nodeConfig: {
            id: uuidv4(),
            renderKey: GROUP_NODE_RENDER_ID,
            groupChildren,
            groupCollapsedSize: { width: 200, height: 40 },
            label: '新建群组',
          },
        })
      },
    })

    /** 解散群组 */
    iconToolbarGroup.push({
      tooltip: '解散群组',
      iconName: 'UngroupOutlined',
      id: XFlowGroupCommands.DEL_GROUP.id,
      isEnabled: state.isGroupSelected,
      onClick: async ({ commandService, modelService }) => {
        const cell = await MODELS.SELECTED_NODE.useValue(modelService)
        const nodeConfig = cell.getData()
        commandService.executeCommand<NsGroupCmd.AddGroup.IArgs>(XFlowGroupCommands.DEL_GROUP.id, {
          nodeConfig: nodeConfig,
        })
      },
    })

    /** 已保存下拉选择 */
    operToolbarGroup.push({
      iconName: 'FolderOpenOutlined',
      id: XFlowGraphCommands.LOAD_DATA.id,
      render: props => {
        const items: MenuProps['items'] = []
        db.graphs.toArray(graps => {
          graps.map(grap => {
            items.push({
              key: grap.id,
              label: (
                <div>
                  <span className='hoverChangeColor' style={{ display: 'inline-block', width: "100px" }} onClick={() => choiceGraph(grap.id)} >{grap.name ? grap.name : '未命名'}</span>
                  <CloseOutlined className='hoverChangeColor' style={{ margin: "5px 0 0 10px", float: "right", fontSize: "12px" }} onClick={() => deleteGraph(grap.id)} />
                </div>
              ),
            })
          })
        })

        const app = useXFlowApp()
        async function choiceGraph(id) {
          const grap = await db.graphs.get(parseInt(id))

          const grapData = {
            id: grap.id,
            text: grap.name,
            data: JSON.parse(grap.data)
          }

          // useEffect(() => {
          //   setGraphData({
          //     id: grap.id,
          //     text: grap.name,
          //     data: JSON.parse(grap.data)
          //   })
          // })

          // console.log(graphData)
          app.executeCommand(XFlowGraphCommands.GRAPH_RENDER.id, {
            graphData: grapData.data,
          } as NsGraphCmd.GraphRender.IArgs)
        }

        function deleteGraph(id) {
          MessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            db.graphs.delete(id)
            Message({ type: 'success', message: '删除成功!' });
          }).catch(() => {

          })
        }
        return (
          <Dropdown menu={{ items }} >
            <Space>
              {props.children}
            </Space>
          </Dropdown>
        )
      },
    })

    /** 保存数据 */
    operToolbarGroup.push({
      tooltip: '保存',
      iconName: 'SaveOutlined',
      id: XFlowGraphCommands.SAVE_GRAPH_DATA.id,
      onClick: async ({ commandService }) => {
        commandService.executeCommand<NsGraphCmd.SaveGraphData.IArgs>(XFlowGraphCommands.SAVE_GRAPH_DATA.id, {
          saveGraphDataService: (meta, graphData: NsGraph.IGraphData) => {

            // useEffect(() => {

            // })

            // if (graphCurrent.id != 0) {
            //   const grapJson = JSON.stringify(graphData)
            //   db.graphs.update(graphCurrent.id,
            //     {
            //       "name": graphCurrent.text,
            //       "update_time": new Date(),
            //       "data": grapJson
            //     }
            //   )
            // } else {
            MessageBox.prompt('请输入名称', '提示').then(({ value }) => {
              const grapJson = JSON.stringify(graphData)
              db.graphs.add(
                {
                  "type": "flow",
                  "name": value,
                  "update_time": new Date(),
                  "data": grapJson
                }
              )
            }).catch((err) => {
              // console.log(err)
            });
            // }
            return null
          },
        },
        )
      },
    })

    titleToolbarGroup.push({
      id: "titleToolbarGroup",
      // text: graphDataRef?.current?.text,
      render: props => {
        return (
          <div></div>
        )
      }
    })

    return [
      {
        name: 'operToolbarGroup',
        items: operToolbarGroup,
      },
      {
        name: 'iconToolbarGroup',
        items: iconToolbarGroup,
      },
      {
        name: 'titleToolbarGroup',
        items: titleToolbarGroup,
      },
    ]
  }
}

/** 注册icon 类型 */
const registerIcon = () => {
  IconStore.set('SaveOutlined', SaveOutlined)
  IconStore.set('UndoOutlined', UndoOutlined)
  IconStore.set('RedoOutlined', RedoOutlined)
  IconStore.set('VerticalAlignTopOutlined', VerticalAlignTopOutlined)
  IconStore.set('VerticalAlignBottomOutlined', VerticalAlignBottomOutlined)
  IconStore.set('GatewayOutlined', GatewayOutlined)
  IconStore.set('GroupOutlined', GroupOutlined)
  IconStore.set('UngroupOutlined', UngroupOutlined)
  IconStore.set('CopyOutlined', CopyOutlined)
  IconStore.set('SnippetsOutlined', SnippetsOutlined)
  IconStore.set('FolderOpenOutlined', FolderOpenOutlined)
}

export const useToolbarConfig = createToolbarConfig((toolbarConfig, proxy) => {
  registerIcon()

  /** 生产 toolbar item */
  toolbarConfig.setToolbarModelService(async (toolbarModel, modelService, toDispose) => {

    const updateToolbarModel = async (graphModel) => {
      const state = await NSToolbarConfig.getToolbarState(modelService, graphModel)
      const toolbarItems = await NSToolbarConfig.getToolbarItems(state, modelService)

      toolbarModel.setValue(toolbar => {
        toolbar.mainGroups = toolbarItems
      })
    }
    const models = await NSToolbarConfig.getDependencies(modelService)
    const subscriptions = models.map(model => {
      return model.watch(async () => {
        updateToolbarModel(model)
      })
    })
    toDispose.pushAll(subscriptions)
  })
})
